const express = require('express');
const fs = require('fs');
const path = require('path');
const router = express.Router();  // 创建一个路由实例

// 文件上传的处理逻辑
const upload = (req, res) => {
  let fileObj = null;
  let filePath = '';

  if (!req.files || Object.keys(req.files).length === 0) {
    return res.status(400).send({
      code: 1,
      msg: 'No file uploaded or bad request.'
    });
  }

  fileObj = req.files.file;
  filePath = './upload/' + fileObj.name;

  // 检查 upload 文件夹是否存在，如果不存在则创建
  const uploadFolder = path.join(__dirname, '../upload');
  if (!fs.existsSync(uploadFolder)) {
    fs.mkdirSync(uploadFolder);
  }

  fileObj.mv(filePath, (err) => {
    if (err) {
      return res.status(500).send({
        code: 1,
        msg: 'System error during file upload.'
      });
    }

    res.send({
      code: 0,
      msg: 'Upload Successfully',
      data: {
        fileName: fileObj.name,
        filePath: filePath
      }
    });
  });
};

// 注册路由
router.post('/upload', upload);

module.exports = router;
